package com.hzpd.hainan.module.news.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.hzpd.hainan.R;
import com.hzpd.hainan.api.InterfaceJsonfile;
import com.hzpd.hainan.app.ToolBarActivity;
import com.hzpd.hainan.config.CODE;
import com.hzpd.hainan.model.news.HotSearchBean;
import com.hzpd.hainan.model.news.HotSearchEntity;
import com.hzpd.hainan.model.news.NewsBean;
import com.hzpd.hainan.model.news.NewsListEntity;
import com.hzpd.hainan.model.news.SearchHisBean;
import com.hzpd.hainan.module.news.adapter.ListDataSetObserver;
import com.hzpd.hainan.module.news.adapter.NewsItemListViewAdapter;
import com.hzpd.hainan.module.news.adapter.SearchRecordAdapter;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.utils.AAnim;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.StringUtils;
import com.hzpd.hainan.utils.TUtils;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/7/6.
 */

public class SeachActivity extends ToolBarActivity {
    @BindView(R.id.search_listview_id)
    PullToRefreshListView search_listview_id;
    @BindView(R.id.search_edittext_id)
     EditText search_edittext_id;

    @BindView(R.id.search_clear_ll)//clear button
     LinearLayout search_clear_ll;

    @BindView(R.id.text_search_id)//搜索 按钮
     TextView text_search_id;
    @BindView(R.id.text_remove_id)//取消 按钮
     TextView text_remove_id;




    @BindView(R.id.search_record_lv)
     ListView search_record_lv;
    @BindView(R.id.ll_root_id)
     LinearLayout ll_root_id;
    @BindView(R.id.search_grid_id)
     GridView search_grid_id;
    @BindView(R.id.tv_title)
    TextView tv_title;

    @BindView(R.id.search_hot_tv)
    TextView search_hot_tv;
    @BindView(R.id.search_history_tv)
    TextView search_history_tv;
    private NewsItemListViewAdapter adapter;
    private SearchRecordAdapter recordAdapter;
    private GridViewAdapter adapter2;
//    private SearchRecordDbTask searchTask;
    private boolean isRefresh=false;
    private int page=1;
    private static final int pageSize=15;
    @Override
    public String initToolBarTitle() {
        return null;
    }

    @Override
    public int setMyContentView() {
        return R.layout.search_main_layout;
    }

    @Override
    public void initView() {

        if (spu.getLanguage().equals(CODE.ZHONGWEN)) {
            tv_title.setText("海南报");
            search_edittext_id.setHint("输入关键字");
            text_remove_id.setText("取消");
            text_search_id.setText("搜索");
            search_hot_tv.setText("热门搜索");
            search_history_tv.setText("搜索历史");
        }else{
            tv_title.setText("མཚོ་ལྷོའི་ཚགས་པར།");
            search_edittext_id.setHint("གནད་ཚིག་གཏག་པ།");
            text_remove_id.setText("ཕྱིར་འཐེན།");
            text_search_id.setText("འཚོལ་བཤེར།");
            search_hot_tv.setText("ནང་དོན་ཚ་ཤོས།");
            search_history_tv.setText("ཟིན་ཐོ་འཚོལ་བཤེར།");
        }

        search_listview_id.setVisibility(View.GONE);
        adapter2 = new GridViewAdapter(this);
        search_grid_id.setAdapter(adapter2);
        getHotSearchData();
        adapter=new NewsItemListViewAdapter(activity);
        search_listview_id.setAdapter(adapter);
        search_listview_id.setMode(PullToRefreshBase.Mode.DISABLED);
        recordAdapter = new SearchRecordAdapter(activity);
        recordAdapter.registerDataSetObserver(new ListDataSetObserver(search_record_lv));
        search_record_lv.setAdapter(recordAdapter);
        search_listview_id.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                String con=search_edittext_id.getText().toString();
                if(null==con||"".equals(con)){
                    TUtils.toast("请输入内容");
                    search_listview_id.setMode(PullToRefreshBase.Mode.DISABLED);
                    return;
                }
                new SearchHisBean(con).save();
//                searchTask.addKeyword(con);
                isRefresh=true;
                page=1;
                getSearchData(con);
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                String con=search_edittext_id.getText().toString();
                if(null==con||"".equals(con)){
                    TUtils.toast("请输入内容");
                    return;
                }

                isRefresh=false;
                page++;
                getSearchData(con);
            }
        });
        search_grid_id.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String  data = ((HotSearchBean) adapter2.getItem(position)).getContent();
                search_edittext_id.setText(data);
                ll_root_id.setVisibility(View.GONE);
                reflushListView();
            }
        });

    search_edittext_id.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void afterTextChanged(Editable s) {
            String ss=s.toString();
            if(ss.length()>0){
                search_clear_ll.setVisibility(View.VISIBLE);
                text_search_id.setVisibility(View.VISIBLE);
                text_remove_id.setVisibility(View.GONE);
                ll_root_id.setVisibility(View.GONE);
                adapter.clear();
                adapter.notifyDataSetChanged();
            }
            else if(TextUtils.isEmpty(ss)){
                search_clear_ll.setVisibility(View.GONE);
                text_search_id.setVisibility(View.GONE);
                text_remove_id.setVisibility(View.VISIBLE);
                ll_root_id.setVisibility(View.VISIBLE);
                udaptRecodeListView();
                adapter.clear();
                adapter.notifyDataSetChanged();
            }
        }
    });
		search_edittext_id.setOnEditorActionListener(new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if(actionId == EditorInfo.IME_ACTION_SEARCH){
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if(inputMethodManager.isActive()){
                    inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
                ll_root_id.setVisibility(View.GONE);
                reflushListView();
                return true;

            }
            return false;
        }
    });
		search_edittext_id.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){
                /*隐藏软键盘*/
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if(inputMethodManager.isActive()){
                    inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
                if (StringUtils.isEmpty(search_edittext_id.getText().toString())){
                    reflushListView();
                }
                return true;
            }
            return false;
        }
    });

		search_listview_id.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
            NewsBean nb=(NewsBean) adapter.getItem(position-1);
            Intent mIntent = new Intent();
            mIntent.putExtra("newbean", nb);
            mIntent.putExtra("from", "newsitem");
            TextView title =(TextView) view.findViewById(R.id.newsitem_title);
            if(null!=title){
                title.setTextColor(getResources().getColor(R.color.grey_font));
            }
            //1新闻  2图集  3直播 4专题  5关联新闻 6视频
            if("1".equals(nb.getRtype())){
                mIntent.setClass(activity,NewsHtmlDetailActivity.class);
            }else if("2".equals(nb.getRtype())){
                mIntent.setClass(activity,NewsAlbumActivity.class);
            }
//            else if("3".equals(nb.getRtype())){
//                mIntent.setClass(activity, HtmlActivity.class);//直播界面
//            }else if("4".equals(nb.getRtype())){
//                mIntent.setClass(activity, ZhuanTiActivity.class);
//            }else if("5".equals(nb.getRtype())){
//                mIntent.setClass(activity,XF_NewsHtmlDetailActivity.class);
//            }else if("6".equals(nb.getRtype())){
//                mIntent.setClass(activity,XF_NewsHtmlDetailActivity.class);
//            }else if("7".equals(nb.getRtype())){
//                mIntent.setClass(activity,HtmlActivity.class);
//            }else{
//                return;
//            }
            activity.startActivityForResult(mIntent,0);
            AAnim.ActivityStartAnimation(activity);
        }
    });
    	search_record_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String con = (String) recordAdapter.getItem(position);
            search_edittext_id.setText(con);
            ll_root_id.setVisibility(View.GONE);
            reflushListView();
        }
    });
    }

    @OnClick({R.id.search_ll,R.id.search_clear_tv,R.id.text_remove_id,R.id.text_search_id,R.id.search_clear_ll})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.search_ll:
                String con=search_edittext_id.getText().toString();
                if(null==con||"".equals(con)){
                    TUtils.toast("请输入内容");
                    search_listview_id.setMode(PullToRefreshBase.Mode.DISABLED);
                    return;
                }
                ll_root_id.setVisibility(View.GONE);
                new SearchHisBean(con).save();
                InputMethodManager inputMethodManager=(InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(search_edittext_id.getWindowToken(), 0);
                reflushListView();
                break;
            case R.id.search_clear_tv://清楚历史
                DataSupport.deleteAll(SearchHisBean.class);
                recordAdapter.clear();
                recordAdapter.notifyDataSetChanged();
                break;
            case R.id.text_remove_id://取消
                this.finish();
//				ll_root_id.setVisibility(View.VISIBLE);
//				adapter.clear();
//				search_edittext_id.setText("");
//				adapter.notifyDataSetChanged();
                break;
            case R.id.text_search_id://搜索
                ll_root_id.setVisibility(View.GONE);
                reflushListView();
                break;
            case R.id.search_clear_ll:
                LogUtils.i("clear-->");
                search_clear_ll.setVisibility(View.GONE);
                text_remove_id.setVisibility(View.VISIBLE);
                text_search_id.setVisibility(View.GONE);
                search_edittext_id.setText("");
                adapter.clear();
                adapter.notifyDataSetChanged();
                break;
        }
    }
    private  void reflushListView(){
        LogUtils.i("pull--visible");
        search_listview_id.setVisibility(View.VISIBLE);
        search_listview_id.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        search_listview_id.postDelayed(new Runnable() {
            @Override
            public void run() {
                search_listview_id.setRefreshing(true);
            }
        }, 400);
    }
    private void udaptRecodeListView() {
        final List<SearchHisBean> list = DataSupport.findAll(SearchHisBean.class);
        LogUtils.i("list-->"+list.size());
        if (null != list && list.size() > 0) {
            Collections.reverse(list);
        }
        LogUtils.i("收藏数据--->"+null);
        if (null != list && list.size()>0) {
            LogUtils.i("收藏数据--->"+list.get(0).toString());
            ll_root_id.setVisibility(View.VISIBLE);
            search_listview_id.setVisibility(View.GONE);
            recordAdapter.appendData(list,true);
            recordAdapter.notifyDataSetChanged();
            search_record_lv.setAdapter(recordAdapter);
        }else {
//			search_listview_id.setVisibility(View.GONE);
//			ll_root_id.setVisibility(View.VISIBLE);
        }
    }
    //獲取熱門搜索
    private void getHotSearchData(){
        Map<String,String> map = new HashMap<>();
        map.put("siteid",InterfaceJsonfile.SITEID);
        Factory.provideHttpService().newsHotSearchnew(map)
                .subscribeOn(Schedulers.io())
                .filter(new Func1<HotSearchEntity, Boolean>() {
                    @Override
                    public Boolean call(HotSearchEntity entity) {
                        LogUtils.i("hotcode-->"+entity.code);
                        if ("200".equals(entity.code)){
                            return true;
                        }else{
                            return false;
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<HotSearchEntity>() {
                    @Override
                    public void call(HotSearchEntity entity) {
                        List<HotSearchBean> mylist = entity.data;
                        LogUtils.i("hotbean-->"+mylist.size());
                        if ("200".equals(entity.code)){
                            if(null==mylist){
                                TUtils.toast("暂无数据");
                                return;
                            }
                            List<HotSearchBean> mylist2 =new ArrayList<HotSearchBean>();
                            for (int i=0;i<4;i++) {
                                mylist2.add(mylist.get(i) );
                            }
                            adapter2.setData(mylist2);
                            adapter2.notifyDataSetChanged();
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });


    }
    private void getSearchData(String content){
        Map<String,String> map = new HashMap<>();

        map.put("siteid",InterfaceJsonfile.SITEID);
        if (spu.getUser()!=null){
            map.put("uid","31");
        }
        map.put("content",content);
        map.put("Page",page+"");
        map.put("PageSize",pageSize+"");
        Factory.provideHttpService().newsSearch(map)
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsListEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsListEntity entity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsListEntity>() {
                    @Override
                    public void call(NewsListEntity entity) {
                        search_listview_id.onRefreshComplete();
                        if ("200".equals(entity.code)){
                            List<NewsBean> l=entity.data;
                            if(null==l){
                                TUtils.toast("暂无数据");
                                return;
                            }
                            adapter.appendData(l, isRefresh);
                            if(l.size() < pageSize){
                                search_listview_id.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            }else{
                                search_listview_id.setMode(PullToRefreshBase.Mode.BOTH);
                            }
                            LogUtils.e("size-->"+l.size());
                            adapter.notifyDataSetChanged();
                        }else{
                            if(!isRefresh){
                                page--;
                            }
                            search_listview_id.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        TUtils.toast("服务器未响应");
                        LogUtils.i("throwable-->"+throwable);
                        search_listview_id.onRefreshComplete();
                        if(!isRefresh){
                            page--;
                        }
                        search_listview_id.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    }
                });
    }

    @Override
    public void initData() {
    }

    private class GridViewAdapter extends BaseAdapter {
        List<HotSearchBean> listhot;
        protected LayoutInflater inflater;

        public GridViewAdapter(Context context) {
            inflater = LayoutInflater.from(context);
            listhot = new ArrayList<>();
        }
        public void setData(List<HotSearchBean> listhot){
            this.listhot= listhot;
        }
        @Override
        public int getCount() {
            return listhot.size();
        }

        @Override
        public Object getItem(int position) {
            return listhot.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView==null){
                convertView =inflater.inflate(R.layout.gride_item,null);
            }
            TextView  textView = (TextView) convertView.findViewById(R.id.gride_item_id);
            textView.setText(listhot.get(position).getContent());
            return convertView;
        }

    }
}
